package routers

import (
	"context"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/route"
	"hertz/api"
	"hertz/pojo"
	myUtils "hertz/utils"
)

func loadFavourite(h *route.RouterGroup) {
	favourite := h.Group("/favourite")
	{
		favourite.POST("/action/", updateFavourite)
		favourite.GET("/list/", getFavouriteList)
	}
}

func updateFavourite(c context.Context, ctx *app.RequestContext) {
	favouriteAction := myUtils.GetParamFavourite(ctx)

	// 鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     favouriteAction.Token,
		Operation: "UPDATE_FAVOURITE",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	if favouriteAction.ActionType == "1" {
		_, err := favouriteProvider.Add(c, &api.Favourite{
			UserId:  user.Id,
			VideoId: transInt64(favouriteAction.VideoId),
		})
		if err != nil {
			FAIL(ctx, err)
			return
		}

		OK(ctx, nil)
	} else {
		_, err := favouriteProvider.Del(c, &api.Favourite{
			UserId:  user.Id,
			VideoId: transInt64(favouriteAction.VideoId),
		})
		if err != nil {
			FAIL(ctx, err)
			return
		}

		OK(ctx, nil)
	}
}

func getFavouriteList(c context.Context, ctx *app.RequestContext) {
	favouriteAction := myUtils.GetParamFavourite(ctx)

	// 鉴权
	user, err := userProvider.Authenticate(c, &api.Token{
		Token:     favouriteAction.Token,
		Operation: "UPDATE_FAVOURITE",
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	videoIdList, err := favouriteProvider.FindUserFavouriteList(c, &api.Favourite{
		UserId: user.GetId(),
	})
	if err != nil {
		FAIL(ctx, err)
		return
	}

	var list []pojo.Video
	for _, value := range videoIdList.GetVideoIdList() {
		video, _ := videoProvider.GetVideoById(c, &api.Video{Id: value})
		list = append(list, transVideo(user, video.GetList()[0]))
	}

	OK(ctx, utils.H{"video_list": list})
}
